﻿using Autofac;
using Autofac.Extensions.DependencyInjection;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Silky.Core;
using Silky.Core.Extensions;
using Silky.Core.Modularity;
using System;
using System.IO;

namespace Microsoft.Extensions.Hosting
{
    public static class HostBuilderExtensions
    {
        public static IHostBuilder RegisterSilkyServices<T>(this IHostBuilder builder) where T : StartUpModule
        {
            IEngine engine = null;
            IServiceCollection services = null;
            builder.UseServiceProviderFactory(new AutofacServiceProviderFactory())
                .UseContentRoot(Directory.GetCurrentDirectory())
                .ConfigureServices((hostBuilder, sc) =>
                {
                    //加载Modules以及其他
                    engine = sc.AddSilkyServices<T>(hostBuilder.Configuration,
                        hostBuilder.HostingEnvironment);
                    services = sc;
                })
                .ConfigureContainer<ContainerBuilder>(builder =>
                {
                    engine.RegisterModules(services, builder);
                    engine.RegisterDependencies(builder);
                })
                .ConfigureAppConfiguration((hosting, config) =>
                {
#if DEBUG
                    hosting.HostingEnvironment.EnvironmentName = "Development";
                    Console.WriteLine("start env: " + hosting.HostingEnvironment.EnvironmentName);
#endif
                    config.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                        .AddJsonFile($"appsettings.{hosting.HostingEnvironment.EnvironmentName}.json", optional: true,
                            true);
                    //var c = config.Build();
                    //var configCenterData = c.GetSection("ConfigCenter");
                    //if (configCenterData?.Get<string>() == "Nacos")
                    //{
                    //    // 从配置文件读取Nacos相关配置
                    //    // 默认会使用JSON解析器来解析存在Nacos Server的配置
                    //    config.AddNacosV2Configuration(c.GetSection("NacosConfig"));
                    //}
                    //else if (configCenterData?.Get<string>() == "Apollo")
                    //{
                    //    var apolloData = c.GetSection("ApolloConfig").Get<ApolloOptions>();
                    //    config.AddApollo(c.GetSection("ApolloConfig"))
                    //     ;
                    //}
                    config.AddEnvironmentVariables();
                })
                ;

            return builder;
        }

        public static bool IsEnvironment(this IHostBuilder builder, string environmentName)
        {
            return EngineContext.Current.IsEnvironment(environmentName);
        }
    }
}